package com.leexuan.ordersystem.actions;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.leexuan.ordersystem.beans.Invoice;
import com.leexuan.ordersystem.beans.Money;
import com.leexuan.ordersystem.db.InvoiceDB;
import com.leexuan.ordersystem.db.MoneyDB;
import com.leexuan.ordersystem.forms.MoneyForm;

public class AddMoney2Action extends Action {

	public AddMoney2Action() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		MoneyForm fm = (MoneyForm) form;

		Money st = new Money();

		st.setAccount(fm.getAccount());
		st.setIid(fm.getIid());

		Date date = new Date();

		SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		st.setDate(bartDateFormat.format(date));

		MoneyDB mdb = new MoneyDB();

		InvoiceDB idb = new InvoiceDB();

		try {

			idb.getConnection();

			Invoice in = idb.getInvoice(fm.getOid());

			if (fm.getAccount() > in.getRemain()) {

				ActionErrors errors = new ActionErrors();
				errors.add("OverMoney", new ActionMessage("error.money.OverMoney"));
				saveErrors(request, errors);

				HttpSession session = request.getSession();
				session.setAttribute("oid", Integer.toString(fm.getOid()));

				return mapping.findForward("failure");

			}

			idb.getConnection();

			idb.subInvoiceRemain(fm.getAccount(), fm.getIid());

			mdb.getConnection();

			mdb.addMoneyr(st);

			HttpSession session = request.getSession();
			session.setAttribute("oid", Integer.toString(fm.getOid()));

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				mdb.closeConnection();
				idb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
